package org.jeecg.modules.wmhb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.mapper.WmItemMapper;
import org.jeecg.modules.wmhb.service.IWmItemService;
import org.jeecg.modules.wmhb.service.IWmProductBomService;
import org.jeecg.modules.wmhb.vo.WmBuyVo;
import org.jeecg.modules.wmhb.vo.WmMaterialVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.UserConstant;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 物料产品表
 * @Author: jeecg-boot
 * @Date:   2024-08-31
 * @Version: V1.0
 */
@Service
public class WmItemServiceImpl extends ServiceImpl<WmItemMapper, WmItem> implements IWmItemService {
    @Autowired
    private IWmProductBomService wmProductBomService;

    @Override
    public String checkItemCodeUnique(WmItem wmItem) {
        WmItem item = baseMapper.checkItemCodeUnique(wmItem);
        String itemId = wmItem.getId() == null ? "" : wmItem.getId();
        if(item != null && !itemId.equals(item.getId())){
            return UserConstant.NOT_UNIQUE;
        }else{
            return UserConstant.UNIQUE;
        }
    }

    @Override
    public String checkItemNameUnique(WmItem wmItem) {
        WmItem item = baseMapper.checkItemNameUnique(wmItem);
        String itemId = wmItem.getId() == null ? "" : wmItem.getId();
        if(item != null && !itemId.equals(item.getId())){
            return UserConstant.NOT_UNIQUE;
        }else{
            return UserConstant.UNIQUE;
        }
    }

    @Override
    public List<SelectTreeModel> queryListByContract(String wmContractId){
        //1、获取阶数为0的合同产品
        LambdaQueryWrapper<WmItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmItem::getWmContractId, wmContractId);
        queryWrapper.eq(WmItem::getLevel, 0);
        List<WmItem> listRoot = baseMapper.selectList(queryWrapper);
        if (listRoot == null || listRoot.size() == 0) {
            throw new JeecgBootException("该合同号【" + wmContractId + "】不存在，请核实!");
        }

        List<SelectTreeModel> treeList = new ArrayList<>();
        for(WmItem wmItem: listRoot){
            SelectTreeModel tree = new SelectTreeModel();
            tree.setKey(wmItem.getId());
            tree.setTitle(wmItem.getName());
            tree.setParentId(null);

            //2、获取产品BOM列表
            List<SelectTreeModel> children = queryBomListByWmItemId(wmItem.getId());
            if(!CollectionUtils.isEmpty(children)) {
                tree.setChildren(children);
                tree.setLeaf(false);
            }
            else{
                tree.setChildren(null);
                tree.setLeaf(true);
            }
            treeList.add(tree);
        }

        return treeList;
    };

    //递归获取产品BOM列表
    private List<SelectTreeModel> queryBomListByWmItemId(String wmItemId){
        List<SelectTreeModel> treeList = new ArrayList<>();
        List<WmProductBom> listProductBom = baseMapper.selectProductBomByWmItemId(wmItemId);
        for(WmProductBom wmProductBom: listProductBom){
            WmItem wmItem = baseMapper.selectById(wmProductBom.getBomItemId());
            SelectTreeModel tree = new SelectTreeModel();
            tree.setKey(wmItem.getId());
            tree.setTitle(wmItem.getName());
            tree.setParentId(wmItemId);

            //2、获取产品BOM列表
            List<SelectTreeModel> children = queryBomListByWmItemId(wmProductBom.getBomItemId());
            if(!CollectionUtils.isEmpty(children)) {
                tree.setChildren(children);
                tree.setLeaf(false);
            }
            else{
                tree.setChildren(null);
                tree.setLeaf(true);
            }
            treeList.add(tree);
        }

        return treeList;
    }

    @Override
    public WmItem selectByCode(String code){
        LambdaQueryWrapper<WmItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmItem::getCode, code).last("LIMIT 1");
        return getOne(queryWrapper);
    };

    @Override
    public WmItem selectByName(String name){
        LambdaQueryWrapper<WmItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmItem::getName, name).last("LIMIT 1");
        return getOne(queryWrapper);
    };

    @Override
    public void setConfirmByBatchNo(String batchNo){
        LambdaUpdateWrapper<WmItem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmItem::getEnableFlag, UserConstant.ENABLE_FLAG_YES).eq(WmItem::getBatchNo, batchNo);
        update(null, updateWrapper);
    };

    @Override
    public Map<String, Object> importWmPurchaseTaskbookBom(PurchaseBom purchaseBom, String batchNo){
        WmItem ItemByCode = null;            //通过物料编码查询的物料产品
        WmItem ItemByCreate = new WmItem();  //新创建的物料产品
        String code = null;                  //物料编码
        String wmItemTypeId = null;          //物料分类ID
        String itemOrProduct = null;         //物料产品标识

        if (!StringUtils.isEmpty(purchaseBom.getCode())) {
            ItemByCode = selectByCode(purchaseBom.getCode());
            code = purchaseBom.getCode();
        }
        else {
            //自动创建编码
            code = (String) FillRuleUtil.executeRule(FillRuleConstant.ITEM, null);
        }

        if (purchaseBom.getItemOrProduct().contains("产品") || purchaseBom.getItemOrProduct().contains("PRODUCT")) {
            //产品
            wmItemTypeId = UserConstant.FINISHED_PRODUCT;
            itemOrProduct = UserConstant.PRODUCT_PRODUCT;
        }
        else {
            //物料
            wmItemTypeId = UserConstant.ITEM_PRODUCT;
            itemOrProduct = UserConstant.PRODUCT_ITEM;
        }

        Map<String, Object> result = new HashMap<>();
        if (ItemByCode != null) {
            //1、产品存在
            result.put("isExist", true);
            result.put("entity", ItemByCode);
        }
        else {
            //2、创建产品
            ItemByCreate.setCode(code);
            ItemByCreate.setName(purchaseBom.getName());
            ItemByCreate.setUnitOfMeasure(purchaseBom.getUnitOfMeasure());
            ItemByCreate.setSpecification(purchaseBom.getSpecification());
            ItemByCreate.setEnableFlag(UserConstant.ENABLE_FLAG_NO);
            ItemByCreate.setBatchNo(batchNo);
            ItemByCreate.setWmItemTypeId(wmItemTypeId);
            ItemByCreate.setItemOrProduct(itemOrProduct);

            //3、保存新产品
            save(ItemByCreate);
            result.put("isExist", false);
            result.put("entity", ItemByCreate);
        }
        return result;
    };

    @Override
    public WmItem importMaterialBom(List<WmMaterialVo> wmMaterialVoList, WmTask wmTask){
        //1、保存父项物料
        WmItem ItemParent = queryByVersion(wmTask);
        if(ItemParent == null) {
            ItemParent = new WmItem();
            ItemParent.setWmItemTypeId(UserConstant.FINISHED_PRODUCT);
            ItemParent.setItemOrProduct(UserConstant.PRODUCT_PRODUCT);
            ItemParent.setCode(wmTask.getCode());
            ItemParent.setName(wmTask.getName());
            ItemParent.setUnitOfMeasure(wmTask.getUnitOfMeasure());
            ItemParent.setSpecification(wmTask.getSpecification());
            ItemParent.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            ItemParent.setBatchNo(wmTask.getCurrentVersion());
            ItemParent.setVersion(wmTask.getCurrentVersion());
            ItemParent.setLevel(0);
            save(ItemParent);
        }

        for(WmMaterialVo wmMaterialVo: wmMaterialVoList){
            //2、保存子项物料
            WmItem ItemChild = new WmItem();
            ItemChild.setWmItemTypeId(UserConstant.MATERIAL_PRODUCT);
            ItemChild.setItemOrProduct(UserConstant.PRODUCT_ITEM);
            ItemChild.setCode(wmMaterialVo.getCode());
            ItemChild.setName(wmMaterialVo.getName());
            ItemChild.setUnitOfMeasure(wmMaterialVo.getUnitOfMeasure());
            ItemChild.setSpecification(wmMaterialVo.getSpecification());
            ItemChild.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            ItemChild.setBatchNo(wmTask.getCurrentVersion());
            ItemChild.setVersion(wmTask.getCurrentVersion());
            ItemChild.setLevel(1);
            save(ItemChild);

            //3、保存产品物料关系
            WmProductBom wmProductBom = new WmProductBom();
            wmProductBom.setWmItemId(ItemParent.getId());
            wmProductBom.setBomItemName(ItemChild.getName());
            wmProductBom.setBomItemId(ItemChild.getId());
            wmProductBom.setBomItemCode(ItemChild.getCode());
            wmProductBom.setBomItemSpec(ItemChild.getSpecification());
            Double bomQuantity = wmMaterialVo.getTotalWeight()/wmTask.getQuantity();
            wmProductBom.setQuantity(bomQuantity);
            wmProductBom.setBatchNo(wmTask.getCurrentVersion());
            wmProductBom.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            wmProductBom.setUnitOfMeasure(ItemChild.getUnitOfMeasure());
            wmProductBomService.save(wmProductBom);
        }

        return ItemParent;
    };

    @Override
    public WmItem importBuyBom(List<WmBuyVo> wmBuyVoList, WmTask wmTask){
        //1、保存父项物料
        WmItem ItemParent = queryByVersion(wmTask);
        if(ItemParent == null) {
            ItemParent = new WmItem();  //新创建的物料产品
            ItemParent.setWmItemTypeId(UserConstant.FINISHED_PRODUCT);
            ItemParent.setItemOrProduct(UserConstant.PRODUCT_PRODUCT);
            ItemParent.setCode(wmTask.getCode());
            ItemParent.setName(wmTask.getName());
            ItemParent.setUnitOfMeasure(wmTask.getUnitOfMeasure());
            ItemParent.setSpecification(wmTask.getSpecification());
            ItemParent.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            ItemParent.setBatchNo(wmTask.getCurrentVersion());
            ItemParent.setVersion(wmTask.getCurrentVersion());
            ItemParent.setLevel(0);
            save(ItemParent);
        }

        for(WmBuyVo wmBuyVo: wmBuyVoList){
            //2、保存子项物料
            WmItem ItemChild = new WmItem();
            ItemChild.setWmItemTypeId(UserConstant.MATERIAL_PRODUCT);
            ItemChild.setItemOrProduct(UserConstant.PRODUCT_ITEM);
            ItemChild.setCode(wmBuyVo.getCode());
            ItemChild.setName(wmBuyVo.getName());
            ItemChild.setUnitOfMeasure(wmBuyVo.getUnitOfMeasure());
            ItemChild.setSpecification(wmBuyVo.getSpecification());
            ItemChild.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            ItemChild.setBatchNo(wmTask.getCurrentVersion());
            ItemChild.setVersion(wmTask.getCurrentVersion());
            ItemChild.setLevel(1);
            save(ItemChild);

            //3、保存产品物料关系
            WmProductBom wmProductBom = new WmProductBom();
            wmProductBom.setWmItemId(ItemParent.getId());
            wmProductBom.setBomItemName(ItemChild.getName());
            wmProductBom.setBomItemId(ItemChild.getId());
            wmProductBom.setBomItemCode(ItemChild.getCode());
            wmProductBom.setBomItemSpec(ItemChild.getSpecification());
            wmProductBom.setQuantity(wmBuyVo.getQuantity()/wmTask.getQuantity());
            wmProductBom.setBatchNo(wmTask.getCurrentVersion());
            wmProductBom.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            wmProductBom.setUnitOfMeasure(ItemChild.getUnitOfMeasure());
            wmProductBomService.save(wmProductBom);
        }

        return ItemParent;
    };

    private WmItem queryByVersion(WmTask wmTask){
        LambdaQueryWrapper<WmItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmItem::getCode, wmTask.getCode());
        if(wmTask.getCurrentVersion() == null){
            queryWrapper.isNull(WmItem::getVersion);
        }
        else{
            queryWrapper.eq(WmItem::getVersion, wmTask.getCurrentVersion());
        }
        queryWrapper.last("LIMIT 1");
        return getOne(queryWrapper);
    };

    @Override
    public Map<String, Object> saveItemWhenAddTask(WmTask wmTask){
        Map<String, Object> result = new HashMap<>();
        //自动生成编码
        if (StringUtils.isEmpty(wmTask.getCode())) {
            String code = (String) FillRuleUtil.executeRule(FillRuleConstant.ITEM, null);
            wmTask.setCode(code);
        }

        WmItem ItemByCreate = new WmItem();              //新创建的物料产品
        String wmItemTypeId = null;                      //物料分类ID
        String itemOrProduct = null;                     //物料产品标识
        WmItem ItemByCode = selectByCode(wmTask.getCode());
        if (wmTask.getItemOrProduct().contains("产品") || wmTask.getItemOrProduct().contains("PRODUCT")) {
            //物料
            wmItemTypeId = UserConstant.ITEM_PRODUCT;
            itemOrProduct = UserConstant.PRODUCT_ITEM;
        }
        else {
            //产品
            wmItemTypeId = UserConstant.FINISHED_PRODUCT;
            itemOrProduct = UserConstant.PRODUCT_PRODUCT;
        }

        if (ItemByCode != null) {
            //1、产品存在
            result.put("isExist", true);
            result.put("entity", ItemByCode);
        }
        else {
            //1、创建产品
            ItemByCreate.setCode(wmTask.getCode());
            ItemByCreate.setName(wmTask.getName());
            ItemByCreate.setUnitOfMeasure(wmTask.getUnitOfMeasure());
            ItemByCreate.setSpecification(wmTask.getSpecification());
            ItemByCreate.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
            ItemByCreate.setWmItemTypeId(wmItemTypeId);
            ItemByCreate.setItemOrProduct(itemOrProduct);

            //2、保存新产品
            save(ItemByCreate);
            result.put("isExist", false);
            result.put("entity", ItemByCreate);
        }

        return result;
    };

    @Override
    public Map<String, Object> saveItemWhenImportContractProduct(BOMNode bomNode, String batchNo, String wmContractId){
        Map<String, Object> result = new HashMap<>();
        WmItem ItemByCode = null;            //通过物料编码查询的物料产品
        WmItem ItemByCreate = new WmItem();  //新创建的物料产品
        String code = null;                  //物料编码
        String wmItemTypeId = null;          //物料分类ID
        String itemOrProduct = null;         //物料产品标识
        if (!StringUtils.isEmpty(bomNode.getCode())) {
            ItemByCode = selectByCode(bomNode.getCode());
            code = bomNode.getCode();
        } else {
            //自动创建编码
            code = (String) FillRuleUtil.executeRule(FillRuleConstant.ITEM, null);
        }

        if (bomNode.getItemOrProduct().contains("产品") || bomNode.getItemOrProduct().contains("PRODUCT")) {
            //产品
            wmItemTypeId = UserConstant.FINISHED_PRODUCT;
            itemOrProduct = UserConstant.PRODUCT_PRODUCT;
        } else {
            //物料
            wmItemTypeId = UserConstant.ITEM_PRODUCT;
            itemOrProduct = UserConstant.PRODUCT_ITEM;
        }

        if (ItemByCode != null) {
            //1、产品存在
            result.put("isExist", true);
            result.put("entity", ItemByCode);
        }
        else {
            //2、创建产品
            ItemByCreate.setCode(code);
            ItemByCreate.setWmContractId(wmContractId);
            ItemByCreate.setName(bomNode.getName());
            ItemByCreate.setUnitOfMeasure(bomNode.getUnitOfMeasure());
            ItemByCreate.setSpecification(bomNode.getSpecification());
            ItemByCreate.setLevel(bomNode.getLevel());
            ItemByCreate.setEnableFlag(UserConstant.ENABLE_FLAG_NO);
            ItemByCreate.setBatchNo(batchNo);
            ItemByCreate.setIsContractProduct(UserConstant.IS_CONTRACT_PRODUCT_YES);
            ItemByCreate.setWmItemTypeId(wmItemTypeId);
            ItemByCreate.setItemOrProduct(itemOrProduct);

            //保存新产品
            save(ItemByCreate);
            result.put("isExist", false);
            result.put("entity", ItemByCreate);
        }

        return result;
    };

    @Override
    public List<WmItem> projectList(){
        return baseMapper.projectList();
    };
}
